import { changeCrewLeader, getRole, getUserListPost, roleListServices } from '@/services/userApi';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Button, Image, message, Space, Tag } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import RegisterForm from './commont/registerForm';
import UserInfoForm from './commont/UserInfoForm';

export default function SupervisionCoursePage() {
  const { initialState } = useModel('@@initialState');
  const { currentUser, loading } = initialState || {};
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isVisibleUserInfoForm, setVisibleUserInfoForm] = useState(false);

  const [roleData, setRoleData] = useState<{ label: string; value: string }[]>([]);
  const [leaderData, setLeaderData] = useState<{ label: string; value: string }[]>([]);
  const [roleListData, setListRoleData] = useState<{ label: string; value: string }[]>([]);

  const [userDetail, setUserDetail] = useState(null);

  const showModal = () => {
    setIsModalVisible(true);
  };

  // 获取 角色列表
  const requestRoleList = useRequest(roleListServices, {
    manual: true,
    loadingDelay: 500,
    onSuccess: (res) => {
      // 数据转换
      res = res.map((item: any) => {
        return { value: item.id, label: item.name };
      });
      message.success('获取成功');
      setListRoleData(res);
    },
    onError: (error) => {
      message.error('获取失败');
    },
    onFinally: () => {
      console.log('finally');
    },
  });

  const handleCancel = () => {
    console.log('handleCancel', isModalVisible);

    setIsModalVisible(false);
  };

  // 获取角色数据
  const getRoleData = useRequest(getRole, {
    manual: true, // 关闭自动请求
    onSuccess: (data: any) => {
      setRoleData(
        data.map((role: any) => ({
          label: role.description,
          value: role.id,
        })),
      );
    },
    onError: () => {
      message.error('获取失败');
    },
  });

  // 修改组员的组长 crewId: number, leaderIds: []
  const handleLeaderChange = useRequest(changeCrewLeader, {
    manual: true, // 不自动请求
    onSuccess: (data: String) => {
      message.success(data);
    },
    onError: () => {
      message.error('修改失败');
    },
  });

  // 根据不同的角色 渲染不同的颜色
  const roleColorMap: { [key: string]: string } = {
    组长: 'gold',
    教师: 'green',
    组员: 'cyan',
  };

  useEffect(() => {
    getRoleData.run();
    requestRoleList.run({ roleName: '组长' });
  }, []);

  const columns = useMemo<ProColumns[]>(
    () => [
      {
        title: 'id',
        dataIndex: 'id',
        key: 'id',
        hideInSearch: true,
      },
      {
        title: '用户名',
        dataIndex: 'nickName',
        key: 'nickName',
      },
      {
        title: '账号',
        dataIndex: 'userName',
        key: 'userName',
      },
      {
        title: '头像',
        dataIndex: 'avator',
        key: 'avator',
        hideInSearch: true,
        render: (_, row) => (
          <Image
            width={50}
            height={50}
            src={row.avator}
            fallback=""
          />
        ),
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
      },
      {
        title: '角色',
        dataIndex: 'roleDescriptions',
        key: 'roleDescriptions',
        search: false,
        renderFormItem: (_, { defaultRender }) => {
          return defaultRender(_);
        },
        render: (_, record) => (
          <Space>
            {record.roleDescriptions.map((role: string) => {
              // console.log(record);
              return (
                <Tag color={roleColorMap[role] || 'blue'} key={role}>
                  {role}
                </Tag>
              );
            })}
          </Space>
        ),
      },
      {
        title: '上级',
        dataIndex: 'leaders',
        key: 'leaders',
        search: false,
        renderFormItem: (_, { defaultRender }) => {
          return defaultRender(_);
        },
        render: (_, record) => (
          <Space>
            {record.leaders != null ? (
              record.leaders.map((user: any) => {
                return (
                  <Tag color={'blue'} key={user.id}>
                    {user.nickName}
                  </Tag>
                );
              })
            ) : (
              <Tag color={'blue'}>{'System'}</Tag>
            )}
          </Space>
        ),
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        valueType: 'select',
        valueEnum: {
          0: {
            text: '禁用',
            status: 'Default',
          },
          1: {
            text: '启用',
            status: 'Success',
          },
        },
      },
      {
        title: '操作',
        valueType: 'option',
        key: 'option',
        render: (_: any, record: any) => [
          <Button
            type="link"
            size="middle"
            onClick={() => {
              const formattedRecord = {
                ...record,
                // roleDescriptions: record.roleDescriptions || [],
                leaders: record.leaders?.map((leader: any) => leader.id) || [],
              };
              setUserDetail(formattedRecord);
              setVisibleUserInfoForm(true);
            }}
          >
            详情
          </Button>,
        ],
      },
    ],
    [false],
  );

  const actionRef = useRef<ActionType>();

  return (
    <PageContainer title="用户管理">
      <ProTable
        columns={columns}
        actionRef={actionRef}
        rowKey="id"
        options={{ fullScreen: true, density: true, setting: true }}
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params: {
            pageSize: number;
            current: number;
          },
          sort,
          filter,
        ) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const msg = await getUserListPost(params);
          return {
            data: msg.records,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: true,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: msg.total,
          };
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={showModal}>
            创建新用户
          </Button>,
        ]}
      />

      <UserInfoForm
        data={userDetail}
        open={isVisibleUserInfoForm}
        roleData={roleData}
        allLeaderData={roleListData}
        allowLeader={currentUser?.role?.includes('crew')}
        onOpenChange={(_open: boolean) => {
          setVisibleUserInfoForm(_open);
          if (!_open) {
            setUserDetail(null);
          }
        }}
        onFinish={(data: { crewId: number; leaderId: [] }) => {
          setVisibleUserInfoForm(false);
          handleLeaderChange.run(data);
          (actionRef?.current as any)?.reload();
        }}
      />

      <RegisterForm
        isModalVisible={isModalVisible}
        handleCancel={handleCancel}
        roleData={roleData}
      />
    </PageContainer>
  );
}
